package com.llt.blog.controller;

import com.llt.blog.constants.Constant;
import com.llt.blog.model.Result;
import com.llt.blog.model.UserInfo;
import com.llt.blog.service.UserService;
import com.llt.blog.utils.JwtUtils;
import com.llt.blog.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Resource
    UserService userService;

    // 登录接口 ---> 登录成功返回data给密钥
    @RequestMapping("/login")
    public Result login(String userName, String password) {
        log.info("正在登录");

        // 校验账号和密码
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("账号或者密码不能为空");
        }

        // 在数据库中查询这个给用户
        UserInfo userInfo = userService.queryUserByName(userName);
        if (userInfo == null || userInfo.getId() == null) {
            return Result.fail("账号或者密码不正确");
        }

        // 验证密码是否正确
        if (!SecurityUtils.verify(password, userInfo.getPassword())) {
            log.error("密码错误");
            return Result.fail("账号或者密码错误");
        }

        // 生成密钥
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constant.USER_CLAIM_ID, userInfo.getId());
        claim.put(Constant.USER_CLAIM_NAME, userInfo.getUserName());

        String token = JwtUtils.genToken(claim);

        log.info("获取当前登录的用户信息: " + userInfo.getUserName());
        return Result.success(token);
    }

    /*
     * 获取当前登录用户信息
     * @date 2024/3/10 12:52
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {


        // 1. 获取 token 中的 id
        String token = request.getHeader(Constant.USER_TOKEN_HEADER);
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId == null || userId <= 0) {
            return null;
        }

        // 2. 根据 id 查信息
        UserInfo userInfo = userService.queryUserById(userId);
        if (userInfo != null) {
            userInfo.setPassword("");
        }else {
            return null;
        }

        return userInfo;
    }

    /*
     * 根据 id 获得作者信息
     * @date 2024/3/10 12:52
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {

        log.info("根据id获取用户信息");

        if (blogId == null || blogId < 1) {
            return null;
        }

        UserInfo authorInfoByBlogId = userService.getAuthorInfoByBlogId(blogId);

        if (authorInfoByBlogId != null) {
            authorInfoByBlogId.setPassword("");
        }

        return authorInfoByBlogId;
    }


}
